﻿/**
 * Created by Frank on 12/22/14.
 */
var timer; // declare the timer
var status;
var lessonsPerDay = "";
var lessonTimeWeightChanged = false;
var courseWeightChanged = false;
var lessonTimeWeight = new HashMap();
var courseWeight = new HashMap();
var courseList = null;
var courseWeightMax = 10;

var taskService = new Task();

/**
 * 0(waiting) 1(running) 2(finished) 3(conflict) 4(stopped) 9(failure)
 */

var ruleStatistic = new RuleStatistic();
var ruleMatchingStatistic = new RuleMatchingStatistic();

// 是否是第一次页面加载统计
var firstLoadRuleStatistics = true;

$(function () {
    // 1st leve step
    setTaskStep("auto");
    initDiv(result);

    if (result == 1) {
        timer = window.setInterval("refreshStatus()", 3000);
    }
    //getLessonTimePriority();
    //getCourseList();

    //$("#lessonTimePriority").append(genereteLessonTimePrioirtyUl());

    /*$("div").delegate("select", "change", function () {
        var ids = $(this).prop("id").split("_");
        var selectedValue = $(this).children("option:selected").val();
        console.log(selectedValue);
        if (ids[0] == "lessonTimeWeight") {
            lessonTimeWeightChanged = true;
            lessonTimeWeight.set(ids[1], selectedValue);
        } else if (ids[0] == "courseWeight") {
            courseWeightChanged = true;
            courseWeight.set(ids[1], selectedValue);
        }
    });*/
});

/*function setPreferences() {
    $("#preferences").toggle();
    if ($("#preferencesIcon").hasClass("glyphicon-chevron-down")) {
        $("#preferencesIcon").removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-up");
    } else {
        $("#preferencesIcon").removeClass("glyphicon-chevron-up").addClass("glyphicon-chevron-down");
    }
}
function genereteLessonTimePrioirtyUl() {
    var html = new Array();
    var priority = -1;
    for (var i = 0; i < lessonsPerDay; i++) {
        html.push("<li><label>" + "第" + (i + 1) + "节" + "</label>");
        html.push("<select id='lessonTimeWeight_" + i + "' >");
        priority = lessonTimeWeight.get(i);
        for (var j = 1; j <= lessonsPerDay; j++) {
            if (priority == j) {
                html.push("<option selected='selected' value='" + j + "' >" + j + "</option>");
            } else {
                html.push("<option value='" + j + "' >" + j + "</option>");
            }
        }
        html.push("</select></li>");
    }
    return html.join("");
}

function generateCoursePriorityUl() {
    if (courseList == null || courseList.length == 0) {
        return null;
    }
    var html = new Array();
    var priority = -1;
    for (var i = 0; i < courseList.length; i++) {
        html.push("<li><label>" + courseList[i].name + "</label>");
        priority = courseWeight.get(courseList[i].id);
        html.push("<select id='courseWeight_" + courseList[i].id + "' >");
        html.push("<option value='-1'>默认</option>");
        for (var j = 1; j <= courseWeightMax; j++) {
            if (priority == j) {
                html.push("<option selected='selected' value='" + j + "' >" + j + "</option>");
            } else {
                html.push("<option value='" + j + "' >" + j + "</option>");
            }
        }
        html.push("</select></li>")
    }
    return html.join("");
}
function getCourseList() {
    jQuery.ajax({
        type: "GET",
        url: "/m/jsondata/courses?taskId=" + taskId,
        success: function (ret) {
            courseList = JSON.parse(ret);
            if (courseList == null || courseList.length == 0) {
                $("#coursePriorityDiv").css("display", "none");
            } else {
                getCoursePriority();
                $("#coursePriority").append(generateCoursePriorityUl());
            }
        }
    });
}
function getLessonTimePriority() {
    jQuery.ajax({
        type: "GET",
        url: "/m/rule/lessonTimePriority?taskId=" + taskId,
        async: false,
        success: function (ret) {
            if (ret.code == 1 && ret.data != null) {
                var temp = ret.data.split(",");
                lessonsPerDay = temp.length;
                for (var index = 0; index < lessonsPerDay; index++) {
                    lessonTimeWeight.put(index, temp[index]);
                }
            }
        }
    });
}

function getCoursePriority() {
    jQuery.ajax({
        type: "GET",
        url: "/m/course/coursePriority?taskId=" + taskId,
        async: false,
        success: function (ret) {
            if (ret.code == 1 && ret.data != null) {
                var temp = ret.data;
                for (var i = 0; i < temp.length; i++) {
                    courseWeight.put(temp[i].courseId, temp[i].priority);
                }
            }
        }
    })
}*/


function initDiv(result) {
    $(".operationArea").html(statusDescription(result));
    if (result == 2) {
        loadRuleStatistics();
    }

    if (result == 9) {
        getResultMsg(taskId);
    }

    // 2(finished) 3(conflict)
    // 排课有结果
    if (result == 2 || result == 3) {
        resetPartShedule();
        setPartUnscheduleClassCount();
    } else if (result == 4 || result == 9) {
        setPartUnscheduleClassCount();
    }
    initButton();
}

// 开始任务
function startTask(type) {
//    //先保存课时优先级和 课程优先级
//    if (lessonTimeWeightChanged == true) {
//        var lessonTimePriorityStr = "";
//        var i = 0;
//        for (; i < lessonsPerDay; i++) {
//            if (i == 0) {
//                lessonTimePriorityStr += lessonTimeWeight.get(i);
//            } else {
//                lessonTimePriorityStr += "," + lessonTimeWeight.get(i);
 //           }
 //       }
 //       var res = false;
//        jQuery.ajax({
//            type: "POST",
//            async: false,
//            url: "/m/rule/lessonTimePriority",
//            data: {"taskId": taskId, "lessonTimePriorities": lessonTimePriorityStr},
//            success: function (ret) {
//                res = ret.code == 1 ? true : false;
//            }
//        });
//        if (res == false && !confirm("节次重要性保存失败，是否继续?")) {
//            return;
//        }
//    }
//    if (courseWeightChanged == true) {
//        var keySet = courseWeight.keySet();
//        var arrays = new Array();
//        i = 0;
//        for (; i < keySet.length; i++) {
//            var obj = {};
//            obj.courseId = keySet[i];
//            obj.priority = courseWeight.get(keySet[i]);
//            arrays.push(obj);
//        }
//        var courseWeightStr = JSON.stringify(arrays);
//        jQuery.ajax({
//            type: "POST",
//            async: false,
//            url: "/m/course/coursePriority",
//            data: {"taskId": taskId, "coursePriority": courseWeightStr},
//            success: function (ret) {
 //               res = ret.code == 1 ? true : false;
 //           }
 //       });
 //       if (res == false && !confirm("课程重要性保存失败，是否继续?")) {
 //           return;
 //       }
 //   }
    if (type == 1) {
        if (!confirm("原来的课表将会被清除，确定重新排课吗？")) {
            return;
        }
    }
    initDiv(1); //First,switch the content of the page

    var solverParameters = getSolverParameters();
    taskService.execute(taskId, taskService.solverMethod.convention, solverParameters, function (ret) {
        if (ret == 1) {
            timer = window.setInterval("refreshStatus()", 3000);
        }else {
            initDiv(0);
        }
    });
    //var conditionSettings = {};
    //conditionSettings.solverMethod = taskService.solverMethod;
    //conditionSettings.solverParameters = JSON.stringify(solverParameters);

    //var data={};
    //data.id = taskId;
    //data.conditionSettings = JSON.stringify(conditionSettings);
    //jQuery.ajax({
    //    type: "POST",
    //    url: "/m/task/execute",
    //    data: data,
    //    dataType: "json",
    //    success: function (ret) {
    //        initDiv(1); //First,switch the content of the page
    //        timer = window.setInterval("refreshStatus()", 3000);
    //    }
    //});

}

function initButton() {
    var coursePlanService = new CoursePlanService();
    var hasCoursePlan = 0;
    coursePlanService.hasCoursePlan(taskId, function (has) {
        hasCoursePlan = has;
        $("li[show-by-courseplan='1']").hide();
        if (has == "1") {
            $("li[show-by-courseplan='1']").show();
        }
    })
}

//获取参数
function getSolverParameters() {
    try {
        var unscheduleClassIdList = getUnScheduleClassIdList();
        if (unscheduleClassIdList.length > 0) {
            var solverParameters = {};
            solverParameters.unscheduleClassIdList = unscheduleClassIdList;
            return solverParameters;
        }
    } catch (e) {

    }

    return null;
}

//Added by Tianyu
function stopTask() {
    var r = confirm("你确定要停止排课吗?");
    if (r) {
        $.ajax({
            type: "POST",
            url: "/m/task/stop",
            data: {"id": taskId},
            dataType: "json",
            success: function (e) {
                //e = 1 表示成功
                initDiv(4);
            }
        });
    }

}

/**
 * 状态刷新
 */
function refreshStatus() {
    jQuery.ajax({
        type: "GET",
        url: "/m/task/status?t=" + new Date().getTime(),
        data: {"id": taskId},
        dataType: "json",
        success: function (obj) {
            status = obj;
            if (status == 0 || status >= 2) {
                window.clearInterval(timer);
                initDiv(status);
            }
        }
    });
}

/**
 * 状态描述
 * @param statusValue
 * @returns {*}
 */
function statusDescription(statusValue) {
    var reStartHtml =
        "<div class='text-center'><button class='btn btn-danger' onclick='startTask(1)'>再排一次</button></div>";
    var partUnscheduleHtml =
        "<div class='text-center'><a href='javascript:void();' onclick='setPartSchedule();return false'>不需要重新排课的班级设置</a>" +
        " （<span id='partScheduleCountMsg'>0</span>）</div>";
    /**
     * 0(waiting) 1(running) 2(finished) 3(conflict) 4(stopped) 9(failure)
     */

    var dpaikeMsg =
        // "<p><a class='btn btn-success' style='width: 160px;padding:10px;' href='" + getDpaikeSiteUrl() + "' target='_blank'>试试代排课</a><br><p><p>" +
        "<p><span style='font-size: 14px;margin-top: 5px;color: #619CC5;text-align: left;display: inline-block;margin-top: 40px;'>" +
        "加入云校排课QQ群，了解新高考改革动向~<br>" +
        "专业排课师在线答疑~<br>" +
        // "群号：188318284</span></p>";//群A
        "群号：321446863</span></p>";//群C
    switch (statusValue.toString()) {
        case "0":
            return "<div>" +
                "<button onclick='startTask(0)' class='btn btn-danger'>" +
                "<img src='/static/img/face/smiley_16.png'/>&nbsp;&nbsp; 开始自动排课</button>" +
                "</div>";
        case "1":
            return "<p><img src='/static/img/dong.gif'/>自动排课中~~</p>" +
                "<div><button class='btn btn-danger' onclick='stopTask()'>停止排课</button></div>";
        case "2":
            return "<p><img src='/static/img/face/smiley_21.png'/>排完啦，<a href='/m/courseplan/class?taskId=" + taskId + "'>查看课表</a></p>" +
                "<div id='ruleStatisticsContent'></div>" +
                reStartHtml + partUnscheduleHtml + dpaikeMsg;
        case "3":
            return "<p><img src='/static/img/face/smiley_22.png'/>排完啦，不过其中还存在冲突！<a onclick='checkAndShow(" + taskId + ")'>点此查看<span id='spcheck'></span></a></p>" +
                reStartHtml + partUnscheduleHtml + dpaikeMsg;
        case "4":
            var pushtml = "";
            // 设置了不重排班级
            if (getPartUnscheduleClassCount() > 0) {
                pushtml = partUnscheduleHtml;
            }
            return "<p><img src='/static/img/face/smiley_53.png'/>可能是我想太多了</p>" +
                reStartHtml + pushtml + dpaikeMsg;
        case "9":
            var pushtml = "";
            // 设置了不重排班级
            if (getPartUnscheduleClassCount() > 0) {
                pushtml = partUnscheduleHtml;
            }
            return "<p><img src='/static/img/face/smiley_43.png'/>有点难呢</p><p id='retMsg'>正在查找原因...</p>" +
                reStartHtml + pushtml + dpaikeMsg;
        default :
            return "<p>排课任务不存在</p>";
    }
}

/**
 * 加载统计
 */
function loadRuleStatistics() {
    $("#ruleStatisticsContent").html("正在加载统计");
    ruleStatistic.getFromTaskResult(taskId, function (rs) {
        if (rs == null) {
            if (firstLoadRuleStatistics) {
                firstLoadRuleStatistics = false;
                $("#ruleStatisticsContent").html("");
            } else {
                // 不是第一次页面加载要重试
                // 重新获取
                setTimeout(function () {
                    loadRuleStatistics();
                }, 1000);
            }
            return;
        }

        ruleMatchingStatistic.getStatisticsFromTaskResult(taskId, function (rms) {
            if (rms == null) {
                $("#ruleStatisticsContent").html("");
                return;
            }
            var content =
                "<div>" + rs.requiredTotalCount + "条“必须保证”全部满足，" +
                rs.veryImportantTotalCount + "条“特别重要”满足了" + rms.veryImportantTotalCount + "条，" +
                rs.importantTotalCount + "条“相对重要”满足了" + rms.importantTotalCount + "条，" +
                rs.normalTotalCount + "条“一般”满足了" + rms.normalTotalCount + "条</div>";

            $("#ruleStatisticsContent").html(content);
        })
    })
}

/**
 * 复制任务
 */
function copyTask() {
    $("#myModal").modal('show');
    $("#txtPeriod").val("");
    $("#copyId").val(taskId);
    $("#myModalLabel").html("<b>复用排课任务</b>");

    taskService.getTask(taskId, function (task) {
        $("#txtName").val(task.name + "-副本");
        $("#txtPeriod").val(task.period);
    })
}

/**
 * 添加任务
 */
function addTask() {
    var name = $("#txtName").val();
    var period = $("#txtPeriod").val();
    var copyId = $("#copyId").val();
    if (name == "") {
        alert("请输入名称");
        return;
    }
    $("#btn_save").attr('disabled', true);
    if (copyId != "0") {
        $("#btn_save").html("复制中...");
    }
    $("#btn_cancel").attr('disabled', true);

    taskService.addTask(name, period, copyId, function (taskId) {
        $("#btn_save").removeAttr('disabled');

        if (taskId == 0) {
            alert("复用失败");
        } else {
            location.href = "/m/task/list";
        }
    })
}

/**
 * 获取结果信息
 * @param taskId
 */
function getResultMsg(taskId) {
    var msgCol = $("#retMsg");
    jQuery.ajax({
        url: "/m/task/result?id=" + taskId,
        success: function (ret) {

            ret = processResultMsg(ret);
            // 无解
            if (ret.indexOf("总课时不够") >= 0) {
                msgCol.html("排课出错：" + ret + "<a href='/m/baseInfo/index?taskId=" + taskId + "&action=1" + "'>" + " 点击设置课时 " + "</a>");
            } else {
                msgCol.html("排课出错：" + ret);
            }
        },
        error: function () {
            msgCol.html("抱歉，暂未找到出错原因！");
        }
    });
}

/**
 * 处理结果信息
 * @param ret
 * @returns {*}
 */
function processResultMsg(ret) {
    // 无解
    if (ret == "no result") {
        ret = "在指定的时间内未找到最优解，请适当减少或调整约束，然后再试，祝您好运！";
    } else if (ret.indexOf("初始解") > 0) {
        ret = ret.replace("初始解", "合适排课结果")
    }

    if (ret.indexOf("约束条件") > 0) {
        ret = ret.replace("约束条件", "约束条件（不连堂、不排课规则等）")
    }

    return ret;
}